package org.example;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}


class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public void reorderList(ListNode head) {
        //1.快慢指针找到链表的中点
        ListNode slow = head, fast = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

        //2.对中点右边部分链表进行逆序 （头插法）
        ListNode dummyHead = new ListNode(-1);
        ListNode cur = slow.next;
        slow.next = null;//断开左边部分的链表,以方便第三步操作

        //头插
        while(cur != null){
            ListNode next = cur.next;
            cur.next = dummyHead.next;
            dummyHead.next = cur;
            cur = next;
        }

        //3.合并两个链表
        ListNode dummyRet = new ListNode(-1);
        ListNode cur1 = head, cur2 = dummyHead.next;
        ListNode cur3 = dummyRet;
        while(cur1 != null || cur2 != null){
            if(cur1 != null){
                cur3.next = cur1;
                cur3 = cur3.next;
                cur1 = cur1.next;
            }
            if(cur2 != null) {
                cur3.next = cur2;
                cur3 = cur3.next;
                cur2 = cur2.next;
            }
        }
        head = dummyRet.next;
    }
}